from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_, desc
from app.models.image_task import ImageTask, ImageTaskItem
from app.schemas.image_task import ImageTaskCreate, ImageTaskUpdate, ImageTaskItemCreate
from datetime import datetime

class ImageTaskCRUD:
    def create_task(self, db: Session, task_data: ImageTaskCreate, user_id: int) -> ImageTask:
        """创建图片任务"""
        db_task = ImageTask(
            user_id=user_id,
            task_name=task_data.task_name,
            description=task_data.description
        )
        db.add(db_task)
        db.commit()
        db.refresh(db_task)
        return db_task
    
    def get_task(self, db: Session, task_id: int, user_id: int) -> Optional[ImageTask]:
        """获取图片任务"""
        return db.query(ImageTask).filter(
            and_(ImageTask.id == task_id, ImageTask.user_id == user_id)
        ).first()
    
    def get_user_tasks(self, db: Session, user_id: int, skip: int = 0, limit: int = 100) -> List[ImageTask]:
        """获取用户的图片任务列表"""
        return db.query(ImageTask).filter(
            ImageTask.user_id == user_id
        ).order_by(desc(ImageTask.created_at)).offset(skip).limit(limit).all()
    
    def update_task(self, db: Session, task_id: int, user_id: int, task_data: ImageTaskUpdate) -> Optional[ImageTask]:
        """更新图片任务"""
        db_task = self.get_task(db, task_id, user_id)
        if db_task:
            update_data = task_data.dict(exclude_unset=True)
            for field, value in update_data.items():
                setattr(db_task, field, value)
            db.commit()
            db.refresh(db_task)
        return db_task
    
    def delete_task(self, db: Session, task_id: int, user_id: int) -> bool:
        """删除图片任务"""
        db_task = self.get_task(db, task_id, user_id)
        if db_task:
            db.delete(db_task)
            db.commit()
            return True
        return False
    
    def add_image_to_task(self, db: Session, task_id: int, image_data: Dict[str, Any]) -> ImageTaskItem:
        """向任务添加图片 - 简化版，只保存URL和基本信息"""
        # 只保留必要的字段
        simplified_data = {
            "image_url": image_data.get("image_url"),
            "upload_status": image_data.get("upload_status", "success"),
            "sort_order": image_data.get("sort_order", 0)
            # 移除：cos_url, cos_key, file_size, file_type, width, height等字段
        }
        
        db_image = ImageTaskItem(
            task_id=task_id,
            **simplified_data
        )
        db.add(db_image)
        db.commit()
        db.refresh(db_image)
        return db_image
    
    def update_image_status(self, db: Session, image_id: int, status: str, cos_url: str = None, cos_key: str = None, error_message: str = None) -> Optional[ImageTaskItem]:
        """更新图片状态"""
        db_image = db.query(ImageTaskItem).filter(ImageTaskItem.id == image_id).first()
        if db_image:
            db_image.upload_status = status
            if cos_url:
                db_image.cos_url = cos_url
            if cos_key:
                db_image.cos_key = cos_key
            if error_message:
                db_image.error_message = error_message
            db.commit()
            db.refresh(db_image)
        return db_image
    
    def get_task_images(self, db: Session, task_id: int, user_id: int) -> List[ImageTaskItem]:
        """获取任务的所有图片"""
        return db.query(ImageTaskItem).join(ImageTask).filter(
            and_(ImageTask.id == task_id, ImageTask.user_id == user_id)
        ).order_by(ImageTaskItem.sort_order, ImageTaskItem.created_at).all()

# 创建实例
image_task = ImageTaskCRUD()